﻿#!/usr/bin/python

__author__="liuxianke"
__date__ ="$2012-7-2 13:29:54$"

from datetime import *
import json
import urllib, urllib2

def createActivity(templatefilename, outputfile):
    dt = datetime.today() + timedelta(days=1)
    outputfile.write('Create activity for day:' + dt.strftime("%Y-%m-%d") + '\n')
    day = dt.strftime("%Y%m%d")
    templatefile = open(templatefilename, 'r')
    template = json.load(templatefile)
    templatefile.close()
    activitystaticinfo = template['staticInfo']
    # Create activity id
    id = activitystaticinfo['id']
    if (id<10):
        activityid = int(dt.strftime("%Y%m%d") + '0' + str(activitystaticinfo['id']))
    else:
        activityid = int(dt.strftime("%Y%m%d") + str(activitystaticinfo['id']))
    activitystaticinfo['id'] = activityid
    # Set activity time
    activitystaticinfo['startTime'] = dt.strftime("%Y-%m-%d") + ' 00:00:00'
    activitystaticinfo['endTime'] = dt.strftime("%Y-%m-%d") + ' 23:59:59'
    # Login to gmserver
    configfile = open('config.json', 'r')
    config = json.load(configfile)
    configfile.close()
    outputfile.write('Login: ')
    loginData = {'username':config['user'], 'password':config['password']}
    login = urllib2.urlopen(
            url = config['gmsvrurl'] + r'/login',
            data = json.dumps(loginData)
            #data = urllib.quote(json.dumps(template))
        )
    loginRes = json.loads(login.read())
    json.dump(loginRes, outputfile)
    outputfile.write('\n')
    if (loginRes['result']==0):
        outputfile.write('Add activity: ')
        sessionid = loginRes['sessionid']
        templates = {'normalActivityTemplates':[template]}
        addActivityData = {'sessionid':sessionid, 'server':-1, 'data':templates}
        addActivity = urllib2.urlopen(
                url = config['gmsvrurl'] + r'/addNormalActivity',
                data = json.dumps(addActivityData)
            )
        addActivityRes = json.loads(addActivity.read())
        json.dump(addActivityRes, outputfile)
        outputfile.write('\n')

if __name__ == "__main__":
    outputfile = open('add_activity_card3_result.txt', 'a+')
    outputfile.write('--------------------------------------\n')
    createActivity('addActivityConfig_card3.json', outputfile)
    outputfile.close()